<?php
/**
 * Standard Contact Form
 */
class ContactForm extends Form {
    /**
     * Constructor
     *
     * @param Controller $controller The parent controller, necessary to
     *                               create the appropriate form action tag.
     * @param string $name The method on the controller that will return this
     *                     form object.
     * @param FieldList|FormField $fields All of the fields in the form - a
     *                                   {@link FieldList} of {@link FormField}
     *                                   objects.
     * @param FieldList|FormAction $actions All of the action buttons in the
     *                                     form - a {@link FieldList} of
     */
    function __construct($controller, $name, $fields = null, $actions = null, $validator = null) {
        if(!$fields) {
            $fields = EnquiryRequest::create()->getFrontEndFields();
            $validator = RequiredFields::create('Type', 'Name', 'Email', 'Phone', 'Message');
			if($member = Distributor::currentUser()){
				$fields->dataFieldByName('Name')->setValue($member->getName());
				$fields->dataFieldByName('Email')->setValue($member->Email);
				$fields->dataFieldByName('Phone')->setValue($member->Mobile);
			}
        }

        if(!$actions) {
            $actions = FieldList::create(
            	FormAction::create('doSaveContact', _t('ContactForm.BUTTONSUBMIT', 'Submit'))
			);
        }

        parent::__construct($controller, $name, $fields, $actions, $validator);
    }

    public function doSaveContact($data, $form){
        try {
            $request = EnquiryRequest::create();
            $form->saveInto($request);
            $request->write();
            if(Director::isLive()){
                $request->send();
            }
            $form->sessionMessage(_t('ContactForm.SUCCESS_SENT_INFORMATION', 'Your request has been successfully sent. We will contact you for further information as soon as posibble.'), 'success');
        }
        catch(ValidationException $e) {
            $form->sessionMessage($e->getResult()->message(), 'error');
        }
        
        if($this->request->isAjax()){
            return $this->forTemplate();
        }
        return $this->controller->redirectBack();
    }
}
?>